﻿namespace IBTrader.Charts.Web
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Globalization;
    using System.Linq;

    class WebGraphics : BaseGraphics, IGraphics
    {
        private static readonly CultureInfo en = new CultureInfo("en-US");
        private static readonly CultureInfo ci = CultureInfo.InvariantCulture;
        private Result Items;
        internal Result Draw(IEnumerable<IChart> charts, double width, double height)
        {
            Items = new Result();
            base.Draw(this, charts, width, height);
            return Items;
        }

        #region IGraphics
        void IGraphics.FillPolygon(SolidBrush brush, PointF[] points)
        {
            Items.Add(new Points { Items = points.SelectMany(p => FloatS(p.X, p.Y)), Color = Color(brush.Color) });
        }
        void IGraphics.DrawLines(Pen pen, params PointF[] points)
        {
            Items.Add(new Points { Items = points.SelectMany(p => FloatS(p.X, p.Y)), Color = Color(pen.Color), Width = pen.Width });
        }
        void IGraphics.DrawString(string txt, Font font, SolidBrush brush, PointF point)
        {
            point.Y += 10;
            Items.Add(new Text { Value = txt, Items = FloatS(point.X, point.Y), Color = Color(brush.Color), Font = Font(font) });
        }
        void IGraphics.FillRectangle(SolidBrush brush, RectangleF r)
        {
            Items.Add(new FillRect { Items = FloatS(r.X, r.Y, r.Width, r.Height), Color = Color(brush.Color) });
        }
        void IGraphics.DrawRectangle(Pen pen, Rectangle r)
        {
            Items.Add(new DrawRect { Items = FloatS(r.X, r.Y, r.Width, r.Height), Color = Color(pen.Color) });
        }
        void IGraphics.FillPie(SolidBrush brush, Rectangle r, int startAngle, int sweepAngle)
        {
            Items.Add(new FillPie { Items = FloatS(r.X, r.Y, r.Width, r.Height, startAngle, sweepAngle), Color = Color(brush.Color) });
        }
        void IGraphics.DrawPie(Pen pen, RectangleF r, int startAngle, int sweepAngle)
        {
            Items.Add(new DrawPie { Items = FloatS(r.X, r.Y, r.Width, r.Height, startAngle, sweepAngle), Color = Color(pen.Color), Width = pen.Width });
        }
        private static IEnumerable<string> FloatS(params float[] floats)
        {
            return floats.Select(f => ((int)f).ToString(ci));
        }
        private static Func<Color, string> Color = color => string.Format(en, "rgba({0},{1},{2},{3})", color.R, color.G, color.B, color.A / 255.0);
        private static Func<Font, string> Font = font => string.Format("{0} {1}", font.Size, font.Name);
        #endregion
    }
}
